﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using AtletIS.Shared.AtletisService;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;

namespace AtletIS.Shared.Helpers
{
    public static class UploadHelper
    {
        #region Private methods

        private static DataTable PrepareSimpleTable(DataTable dtInput)
        {
            DataTable dtOutput = new DataTable("SyncTable");
            
            // Add columns
            foreach (DataColumn col in dtInput.Columns)
            {
                dtOutput.Columns.Add(col.ColumnName, col.DataType);
            }

            // Add rows
            foreach (DataRow row in dtInput.Rows)
            {
                dtOutput.Rows.Add();
                DataRow syncRow = dtOutput.Rows[dtOutput.Rows.Count - 1];
                
                foreach (DataColumn col in dtInput.Columns)
                {
                    syncRow[col.ColumnName] = row[col.ColumnName];
                }

                // Change [ID] <--> [WebId]
                if (dtOutput.Columns.Contains("WebId"))
                {
                    int id = Convert.ToInt32(syncRow["ID"]);
                    syncRow["ID"] = syncRow["WebId"];
                    syncRow["WebId"] = id;
                }
            }

            #region ChipTags

            if (dtOutput.Columns.Contains("ChipTagsGroupId"))
            {
                DataTable dtChipTagsGroups = new ChipTagsGroupsTableAdapter().GetData();

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    string filter = "ID = " + syncRow["ChipTagsGroupId"];
                    syncRow["ChipTagsGroupId"] = dtChipTagsGroups.Select(filter)[0]["WebId"];
                }
            }

            #endregion

            #region DisciplineList FKs

            // DisciplineList.CompetitionId
            if (dtOutput.Columns.Contains("CompetitionId"))
            {
                DataTable dtCompetitions = new CompetitionsTableAdapter().GetData();

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    string filter = "ID = " + syncRow["CompetitionId"];
                    syncRow["CompetitionId"] = dtCompetitions.Select(filter)[0]["WebId"];
                }
            }

            // DisciplineList.ParentId
            if (dtOutput.Columns.Contains("ParentId"))
            {
                DataTable dtDisciplineList = DatabaseHelper.GetAllDisciplineListByCompetitionIdAll(Globals.ActiveCompetition.ID); 
                // new DisciplineListTableAdapter().GetByCompetitionIdAll(Globals.ActiveCompetition.ID);

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    if (Convert.ToInt32(syncRow["ParentId"]) != 0)
                    {
                        string filter = "ID = " + syncRow["ParentId"];
                        syncRow["ParentId"] = dtDisciplineList.Select(filter)[0]["WebId"];
                    }
                }
            }

            // DisciplineList.CategoryId
            if (dtOutput.Columns.Contains("CategoryId"))
            {
                DataTable dtCategories = new CategoriesTableAdapter().GetData();

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    string filter = "ID = " + syncRow["CategoryId"];
                    syncRow["CategoryId"] = dtCategories.Select(filter)[0]["WebId"];
                }
            }

            // DisciplineList.DisciplineId
            if (dtOutput.Columns.Contains("DisciplineId"))
            {
                DataTable dtDisciplines = new DisciplinesTableAdapter().GetData();

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    string filter = "ID = " + syncRow["DisciplineId"];
                    syncRow["DisciplineId"] = dtDisciplines.Select(filter)[0]["WebId"];
                }
            }

            #endregion

            // [Performances].[DisciplineListId] / [CheckPoints].[DisciplineListId] / [ExtTexts].[DisciplineListId]
            if (dtOutput.Columns.Contains("DisciplineListId"))
            {
                DataTable dtDisciplineList = DatabaseHelper.GetAllDisciplineListByCompetitionIdAll(Globals.ActiveCompetition.ID); 
                // new DisciplineListTableAdapter().GetByCompetitionIdAll(Globals.ActiveCompetition.ID);

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    if (syncRow["DisciplineListId"] != DBNull.Value)
                    {
                        string filter = "ID = " + syncRow["DisciplineListId"];
                        syncRow["DisciplineListId"] = dtDisciplineList.Select(filter)[0]["WebId"];
                    }
                }
            }

            // [Performances].[CompetitorId]
            if (dtOutput.Columns.Contains("CompetitorId"))
            {
                DataTable dtCompetitors = new CompetitorsTableAdapter().GetData();

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    string filter = "ID = " + syncRow["CompetitorId"];
                    syncRow["CompetitorId"] = dtCompetitors.Select(filter)[0]["WebId"];
                }
            }

            // [ExtTexts].[PerformanceId]
            if (dtOutput.Columns.Contains("PerformanceId"))
            {
                DataTable dtPerformances = DatabaseHelper.GetPerformancesByCompetitionIdAll(Globals.ActiveCompetition.ID); 

                foreach (DataRow syncRow in dtOutput.Rows)
                {
                    if (syncRow["PerformanceId"] != DBNull.Value)
                    {
                        string filter = "ID = " + syncRow["PerformanceId"];
                        syncRow["PerformanceId"] = dtPerformances.Select(filter)[0]["WebId"];
                    }
                }
            }

            // Accept all changes in table
            dtOutput.AcceptChanges();

            foreach (DataRow syncRow in dtOutput.Rows)
            {

                if (dtOutput.Columns.Contains("WebId"))
                {
                    // Sync via [WebId] as [ID]
                    if (Convert.ToInt32(syncRow["ID"]) == 0)
                    {
                        syncRow.SetAdded();
                    }
                    else
                    {
                        syncRow.SetModified();
                    }
                }
                else if (dtOutput.Columns.Contains("Sync"))
                {
                    // Sync via [Sync]
                    if (Convert.ToBoolean(syncRow["Sync"]) == false)
                    {
                        syncRow.SetAdded();
                    }
                    else
                    {
                        syncRow.SetModified();
                    }
                }
            }

            return dtOutput;
        }

        #endregion

        #region Public upload methods

        public static DataTable Upload(DataTable dt, SyncParameters syncParams)
        {
            int error = 0;
            string errorText = string.Empty;

            DataTable dtSync = PrepareSimpleTable(dt);
            using (AtletisServiceClient client = new AtletisServiceClient())
            {
                return client.SetTable(dtSync, syncParams, ref error, ref errorText);
            }
        }

        public static int UploadChipData(DataTable dt)
        {
            int error = 0;
            string errorText = string.Empty;

            DataTable dtSync = PrepareSimpleTable(dt);
            using (AtletisServiceClient client = new AtletisServiceClient())
            {
                return client.SetChipData(dtSync, ref error, ref errorText);
            }
        }

        public static int UploadPreChipData(DataTable dt)
        {
            int error = 0;
            string errorText = string.Empty;

            DataTable dtSync = PrepareSimpleTable(dt);
            using (AtletisServiceClient client = new AtletisServiceClient())
            {
                return client.SetPreChipData(dtSync, ref error, ref errorText);
            }
        }

        #endregion

    }
}
